<template>
  <div v-if="this.user" :class="{ loading: loading }">
    <div>
      <div class="container1" v-if="shoppingCart">
        <span class="zprice">你的购物袋总计 RMB {{ zPrice() }} </span>
      </div>
    </div>
    <div>
      <div class="container2" v-if="shoppingCart">
        <div class="center">
          <div v-for="(pro, i) in shoppingCart" :key="i" class="shopImg">
            <div style="width:200px;height:200px">
                <img class="cpi" :src="pro.img" />
            </div>
            

            <div>
              <span class="cpm" style="overflow: hidden;fontSize:25px;"
                >&nbsp;&nbsp;{{ pro.title }}&nbsp;&nbsp;</span
              >
              <span class="cpm">￥ {{ pro.price * pro.num }}&nbsp;&nbsp;</span>
              <div>
                <!-- <el-input-number v-model="pro.num" @change="handleChange" :min="1" :max="1000" label="描述文字" :data-i='i'>&nbsp;&nbsp;</el-input-number> -->
                <button class="btn1" @click="subProduct(i)" :disabled="pro.num == 1">-</button>
                <input
                  class="sl"
                  type="number"
                  :value="pro.num"
                  min="1"
                  @blur="checkNum(pro,i)"
                    ref="numInput"
                />
                <button class="btn2" @click="addProduct(i)" :disabled="pro.num == 9">+</button>
                <button class="btn3" @click="deleteProduct(pro.id)">
                  删除
                </button>
              </div>
            </div>

          </div>
        </div>

        <div class="pay" v-if="shoppingCart && shoppingCart.length != 0">
          <button @click="Payfor">结账</button>
        </div>
        <div v-else class="pay">
          <p>你还没有添加商品</p>
          <button @click="linktopage('/')">随便逛逛</button>
        </div>
      </div>
    </div>

    <msg-mask ref="msgMaskbtn" />
  </div>
  <div v-else>
  <div class="notLogin">
            <div class="center"> 
                <div class="notLogin-text">
                    <div class="notLogin-icon">
                        <svg t="1663847970228" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6492" width="50" height="50"><path d="M709.492364 742.4 742.4 709.492364 544.907636 512 742.4 314.507636 709.492364 281.6 512 479.092364 314.507636 281.6 281.6 314.507636 479.092364 512 281.6 709.492364 314.507636 742.4 512 544.907636Z" p-id="6493" fill="#d81e06"></path><path d="M1024 512c0-282.763636-229.236364-512-512-512C229.236364 0 0 229.236364 0 512c0 282.763636 229.236364 512 512 512C794.763636 1024 1024 794.763636 1024 512zM46.545455 512C46.545455 254.929455 254.929455 46.545455 512 46.545455s465.454545 208.384 465.454545 465.454545-208.384 465.454545-465.454545 465.454545S46.545455 769.070545 46.545455 512z" p-id="6494" fill="#d81e06"></path></svg>
                    </div>
                    <p>您还没有登录哦！</p>
                </div>
            </div>
  </div>
  </div>
</template>

<script>
import MsgMask from "@/components/MsgMask.vue";
export default {
  components: { MsgMask },
  data() {
    return {
      num: 1,
      user: null,
      shoppingCart: null,
      allPrice: 0,

      //是否选择禁用掉页面的所有点击事件，在删除商品时，就会显示
      loading: false,
    };
  },
  methods: {
    //   handleChange(value) {
    //     console.log(arguments);
    //   },
    //编程时跳转页面方法，一般用来判断是否是重复页面
    linktopage(path) {
      if (this.$route.path == path) {
        return;
      }
      this.$router.push(path);
    },
    subProduct(i) {
      this.shoppingCart[i].num--;
      this.upDatedShoppingCart(this.shoppingCart[i]);
    },
    addProduct(i) {
      this.shoppingCart[i].num++;
      this.upDatedShoppingCart(this.shoppingCart[i]);
    },
    //先获取用户数据
    getUserData() {
      this.user = sessionStorage.getItem("user");
      // 判断是否登录过，否则就直接返回到登录页面
      if (this.user == "" || !this.user) {
        return;
      } else {
        this.user = JSON.parse(this.user);
      }
    },
    //获得用户购物袋数据
    getShoppingCart() {
      if (!this.user) {
        return;
      }
      let url = `http://localhost:3000/shopBagList?userId=${this.user.id}`;
      this.loading = true;
      axios.get(url).then(res => {
        this.shoppingCart = res.data;
        this.loading = false;
        // console.log(res.data);
      });
    },
    //修改购物袋商品数据
    upDatedShoppingCart(pro) {
      this.loading = true;
      let url = `http://localhost:3000/shopBagList/${pro.id}`;
      axios.put(url, pro).then(res => {
        // console.log(res.data)
        this.loading = false;
      });
    },
    //获得总价
    zPrice() {
      let num = 0;
      this.shoppingCart.forEach(e => {
        num += e.price * e.num;
      });
      this.allPrice = num;
      return num;
    },
    //删除某一个商品的功能
    deleteProduct(pid) {
      //由于回调函数里的this会有问题，所以这里提前保存一个变量
      let that = this;
      this.$refs.msgMaskbtn.setInformation({
        title: "确定要删除这个商品吗？",
        btnTitle: "确定",
        callback() {
          let url = `http://localhost:3000/shopBagList/${pid}`;
          this.loading = true;
          axios.delete(url).then(res => {
            console.log(res.data);
            //再次调用自带的获取购物袋信息的方法
            // this.loading = false;
            that.getShoppingCart();
          });
        },
      });
      this.$refs.msgMaskbtn.showbtnMask();
    },
    //删除全部商品的功能
    //此功能直接使用循环会有一个bug，因为删除是有延时，同时大量访问服务器会导致重复过多的访问，
    //因此使用一个递归，单独删除单个数据，在删除后的then方法里进行递归，直到数组为空
    deleteAllProduct() {
      if (this.shoppingCart.length == 0) {
        this.loading = false;
        this.$router.push("/successToPay");
        return;
      }
      let item = this.shoppingCart.pop();
      let url = `http://localhost:3000/shopBagList/${item.id}`;
      axios.delete(url).then(res => {
        console.log(res.data);
        this.deleteAllProduct();
      });
      // console.log(url)
    },

    //购买按钮点击事件
    Payfor() {
      //首先严谨一些，检查是否登录
      if (!this.user) {
        this.$refs.msgMaskbtn.setInformation({
          title: "你还未登录",
          btnTitle: "去登陆",
          callback() {
            this.$router.push("/login");
          },
        });
        this.$refs.msgMaskbtn.showbtnMask();
        return;
      } else {
        //购买功能，用户点击购买后，可以直接清空购物袋的内容，然后转移进订单列表。
        //由于订单列表暂时没完成，所以这里直接将购物袋的内容写到一个order表中
        //这里暂时显示一个提示框，用来代表已完成
        let that = this;
        this.$refs.msgMaskbtn.setInformation({
          title: "确定购买？总价：" + this.zPrice(),
          btnTitle: "确定",
          callback() {
            //购买成功的页面
            //然后清空购物袋
            that.loading = true;
            that.deleteAllProduct();
            // that.shoppingCart = [];
            // that.$router.push("/successToPay")
          },
        });
        this.$refs.msgMaskbtn.showbtnMask();

        // console.log(this.shoppingCart)
      }
    },
    //检查在input框里输入的数据是否正确
    checkNum(pro,i){
        let index = this.$refs.numInput[i];
        let num = parseInt(index.value);
        //判断nan要用isnan

        if(num==''|| isNaN(num) || num <=0 || (typeof num) != 'number'){
            console.log('错误数据')
            pro.num = 1;
            num=1;
            // this.$refs.numInput[i].value = num;
        }else{
            if(num>9){
                num = 9
                pro.num = num;
            }else{
                pro.num = num;
            }
            // this.$refs.numInput[i].value = num;
        }
        this.$refs.numInput[i].value = num;
        this.upDatedShoppingCart(pro);
    }
  },
  mounted() {
    this.getUserData();
    this.getShoppingCart();
    // console.log(this.user)
  },
};


</script>

<style lang="less" scoped></style>
<style scoped src="../assets/css/ShoppingCart.css"></style>
